<form class="layui-form" action="">
  <div class="layui-form-item">
    <label class="layui-form-label">用户名</label>
    <div class="layui-input-block">
      <input type="text" name="title" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
        class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">密码</label>
    <div class="layui-input-inline">
      <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off"
        class="layui-input">
    </div>
    <div class="layui-form-mid layui-word-aux">辅助文字</div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">籍贯</label>
    <div class="layui-input-block">
      <select name="city" lay-verify="required">
        <option value=""></option>
        <option value="0">北京</option>
        <option value="1">上海</option>
        <option value="2">广州</option>
        <option value="3">深圳</option>
        <option value="4">杭州</option>
      </select>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">爱好</label>
    <div class="layui-input-block">
      <input type="checkbox" name="like" title="写作" value="写作">
      <input type="checkbox" name="like" title="阅读" checked value="阅读">
      <input type="checkbox" name="like" title="发呆" value="发呆">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">已婚</label>
    <div class="layui-input-block">
      <input type="checkbox" name="switch" lay-skin="switch">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">性别</label>
    <div class="layui-input-block">
      <input type="radio" name="sex" value="男" title="男">
      <input type="radio" name="sex" value="女" title="女" checked>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">出生日期</label>
    <div class="layui-input-block">
      <input type="text" class="layui-input" id="test1" name="mydate" autocomplete="off">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">头像</label>
    <div class="layui-input-block">
      <input type="file" name="poster" accept="image/*" required>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">相册</label>
    <div class="layui-input-block">
      <input type="file" name="swiper" accept="image/*" multiple>
    </div>
  </div>
  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">自我介绍</label>
    <div class="layui-input-block">
      <textarea id="demo" style="display: none;"></textarea>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
  </div>
</form>

<script>

  //Demo
  layui.use(['layer', 'layedit', 'laydate', 'form', 'jquery'], function () {
    var form = layui.form;
    var $ = layui.jquery;
    var laydate = layui.laydate;
    var layedit = layui.layedit;


    // 配置图片的上传接口
    layedit.set({
      uploadImage: {
        url: '/admin/upload' //接口url
        , type: '' //默认post
      }
    });

    var index = layedit.build('demo'); //建立编辑器


    // form.verify({
    //   username: [
    //     /^[a-zA-Z]{6,12}$/,
    //     '用户名填写不规范'
    //   ]
    // })


    laydate.render({
      elem: '#test1' //指定元素
    });

    // 判断用户名是否存在
    $('input[name="title"]').blur(function(){
      let username = $(this).val();
      if(username){
        $.get('/admin/checkusername',{
          username
        },res=>{
          if(res=='exist'){
            layer.msg("用户名"+username+"已占用");
            $('input[name="title"]').val("");
          }
        })
      }
    })

    //监听提交
    form.on('submit(formDemo)', function (data) {

      try {
        // 获取编辑器中的值

        let content = layedit.getContent(index);
        console.log(content);
        console.log("----------");


        // 获取复选框的值
        let tempArr = [];

        $("input[name='like']:checked").each(function () {
          let res = $(this).val();

          console.log(res);
          tempArr.push(res);
        })

        // 封面
        let poster = $('input[name="poster"]')[0].files[0];
        // 轮播图
        let swiper = $("input[name='swiper']")[0].files;

        console.log(poster);
        console.log(swiper);

        // layer.msg(JSON.stringify(data.field));
        let { title, city, password, sex, isShow, mydate } = data.field;
        console.log(title, city, password, sex, isShow, mydate);
        console.log(data.field);
        isShow = isShow ? 1 : 0;

        /*
        //ajax
        $.post('/admin/add-do', { content, mydate, title, city, password, sex, isShow, like: JSON.stringify(tempArr) }, res => {
          if (res == 'success') {
            // 提示数据已经成功保存
            layer.msg('数据保存成功')
            // 重置表单
            $('form')[0].reset();
            // 重置富文本编辑器
            index = layedit.build('demo');

          } else {
            layer.msg('数据保存失败')
          }
          console.log(res);
        })
        */

        // 使用底层的ajax的写法 模拟表单 异步

        let formData = new FormData();
        // 添加表单数据到formData

        formData.append('content', content)
        formData.append('mydate', mydate)
        formData.append('title', title)
        formData.append('city', city)
        formData.append('password', password)
        formData.append('sex', sex)
        formData.append('isShow', isShow)
        formData.append('like', JSON.stringify(tempArr))
        // formData.append('desc',desc)

        formData.append('poster', poster)
        // 复杂数据类型不支持，需要分解
        for (let i = 0; i < swiper.length; i++) {
          formData.append('swiper', swiper[i])

        }
        // ajax
        $.ajax({
          url: '/admin/add-do',
          method: 'post',
          data: formData,
          dataType: 'text',//希望后端返回的数据的格式
          contentType: false,//不限制表单内容的类型
          processData: false,//发送的数据 不进行序列化操作
          beforeSend: function () {
            console.log("数据发送前的操作");
          },
          // res后端返回的数据
          success: function (res) {
            if (res == 'success') {
              // 提示数据已经成功保存
              layer.msg('数据保存成功')
              // 重置表单
              $('form')[0].reset();
              // 重置富文本编辑器
              index = layedit.build('demo');

            } else {
              layer.msg('数据保存失败')
            }
          },
          error: function (err) {
            console.log(err);
          }

        })

        // 阻止表单提交
        return false;
      } catch (err) {
        console.log(err);
        return false
      }


    });
    form.render();
  });
</script>